<!--
 * @Date: 2021-08-06
 * @LastEditors: fengqi
 * @LastEditTime: 2021-08-24 17:30:36
 * @description: 图片预览组件
 * @param: {
      url: String // 图片链接
      height: Number // 高度
      width: Number // 长度
      size: Number // 没有高度和长度时的默认值
      @click: function // 触发图片点击事件
    }
-->
<template>
  <div class="p--t-8 p--b-8">
    <img
      v-if="!url"
      :style="{
        width: `${width | size}px`,
        height: `${height | size}px`,
      }"
      :src="require('@/assets/images/Imagenotset.png')"
    >
    <div
      v-else
      style="position: relative;display: flex;flexFlow: row wrap;justifyContent: flex-start;"
    >
      <div
        v-for="(item, index) in imgList"
        :key="index"
        class="thumbnail"
        :style="{
          backgroundImage: `url(${item.source}`,
          width: `${width | size}px`,
          height: `${height | size}px`,
        }"
      >
        <div class="mask" @click="handleView(index)">
          <div>
            <i class="el-icon-zoom-in" />
          </div>
        </div>
      </div>
    </div>

  </div>
</template>
<script>
import Bus from '@/utils/bus.js'
export default {
  props: {
    url: {
      type: String,
      default: ''
    },
    height: {
      type: [Number, String],
      default: 40
    },
    width: {
      type: [Number, String],
      default: 40
    },
    size: {
      type: [Number, String],
      default: 64
    },
    list: {
      type: Array,
      default: () => []
    },
    index: {
      type: [String, Number],
      default: 0
    }
  },
  computed: {
    imgList() {
      const sourceImages = []
      for (let i = 0; i < this.list.length; i++) {
        const url = this.list[i].replace(/\s/g, encodeURIComponent(' '))
        sourceImages.push({
          thumbnail: url,
          source: url,
          key: i,
          uid: url
        })
      }
      return sourceImages
    }
  },
  methods: {
    // 图片预览
    handleView(index) {
      Bus.$emit('openBigImg', this.imgList, index)
    }
  }
}
</script>
<style scoped lang="scss">
.thumbnail {
  position: relative;
  background-color: #ffffff;
  /* 从content区域开始显示背景 */
  background-origin: content-box;
  /* 图片上下左右居中 */
  background-position: 50% 50%;
  /* 图像不重复显示 */
  background-repeat: no-repeat;
  /* 保持图像本身的宽高比例，将图片缩放到宽度或高度正好适应定义背景的区域 */
  background-size: contain;
  border-radius: 4px;
  border: solid 1px #dfe4e8;
  box-sizing: border-box;
  display: inline-block;
  overflow: hidden;
  vertical-align: middle;
  .mask {
    position: absolute;
    left: 0;
    top: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-content: center;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.45);
    visibility: hidden;
    cursor: pointer;
    & > div {
      text-align: center;
      ::v-deep .anticon {
        color: #fff;
      }
    }
  }
  &:hover .mask {
    visibility: visible;
  }
}
</style>
